"""
@Project: pythonPro1
@Name: _06histS2.py
@Author: linxin_liu
@Date: 2022/12/2 11:01
"""
import cv2
import numpy as np
from matplotlib import pyplot as plt


def hist_s(image):
    refer = cv2.imread('img_norm.png')
    # gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = image
    ref_gray = cv2.cvtColor(refer, cv2.COLOR_BGR2GRAY)
    hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
    hist_ref = cv2.calcHist([ref_gray], [0], None, [256], [0, 256])
    # 计算累计直方图
    out = np.zeros_like(image)
    tmp_ref = 0.0
    h_ref = hist_ref.copy()
    for i in range(256):
        tmp_ref += h_ref[i]
        h_ref[i] = tmp_ref
    tmp = 0.0
    h_acc = hist.copy()
    for i in range(256):
        tmp += hist[i]
        h_acc[i] = tmp
    # 计算映射
    diff = np.zeros([256, 256])
    for i in range(256):
        for j in range(256):
            diff[i][j] = np.fabs(h_ref[j] - h_acc[i])
    M = np.zeros(256)
    for i in range(256):
        index = 0
        min = diff[i][0]  # min = 1.
        for j in range(256):
            if (diff[i][j] < min):
                min = diff[i][j]
                index = int(j)
        M[i] = index
    outs = M[gray].astype(np.float32)

    return outs


def hist_all(image):
    img_b = image[:, :, 0]
    img_g = image[:, :, 1]
    img_r = image[:, :, 2]
    out_b = hist_s(img_b)
    out_g = hist_s(img_g)
    out_r = hist_s(img_r)
    image[:, :, 0] = out_r
    image[:, :, 1] = out_g
    image[:, :, 2] = out_b
    return image


if __name__ == "__main__":
    img = cv2.imread('D:/tools/image_operation/bing.png')
    out_all = hist_all(img)

    plt.subplot(233)
    plt.title("out")
    plt.imshow(out_all)

    plt.show()
